# coding=utf-8


from os import path
from Effects_Library_treewidget import Ui_MainWindow
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QVBoxLayout, QToolButton, QSizePolicy, QPushButton, \
    QGroupBox, QGridLayout
from PyQt5.QtGui import QIcon, QFont, QPixmap
from PyQt5.QtCore import QPoint, QRect, QSize, Qt  # , pyqtSignal
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets, QtCore
from PyQt5 import QtGui
# PySide2
# PyQt5
import sys
import os
import json
#import maya.mel as mel
#from maya import OpenMayaUI as omui
#from shiboken2 import wrapInstance

#mayaMainWindowPtr = omui.MQtUtil.mainWindow()
#mayaMainWindow = wrapInstance(long(mayaMainWindowPtr), QWidget)  # 鑾峰緱Maya涓荤獥鍙?


class mainWindow(Ui_MainWindow, QMainWindow):

    def __init__(self):
        super(mainWindow, self).__init__()
        #self.setParent(mayaMainWindow)  # 灏嗘柊绐楀彛璁剧疆涓簃aya鐨勫瓙绾?
        #self.setWindowFlags(Qt.Window)
        self.setupUi(self)
        Path = (r"J:/aaa")


        self.dir_level(Path)

    def txt(self, Path):
        iiii = "J:/aaa/qqqq/www"
        aaa = iiii.split("/")


        child1 = QTreeWidgetItem(self.treeWidget)
        child1.setText(0,aaa[1])
        for ooo in aaa:
            child2 = QTreeWidgetItem()
            child2.setText(0, ooo)
            child1.addChild(child2)

    def dir_level(self, Path):


        with open(Path+'/.studiolibrary/database.json', 'r') as a:
            # 读取文件
            result = json.load(a)
            for ii in result.keys():
                value = (result.get(ii))
                #for valueKey in value.keys():
                path = (value.get("path"))
                aaa  = path.split("/")
                aaa.remove("..")
                aaa.remove("..")
                print(aaa)
                for i  in range(len(aaa)):
                    print('111111111')
                    if len(aaa) ==1:
                        print('222222222')
                        if value.get("name")  == aaa[-1]:
                            child1 = QTreeWidgetItem(self.treeWidget)
                            child1.setText(0, aaa[-1])
                    else:
                            child2 = QTreeWidgetItem()
                            child2.setText(0, aaa[-1])
                            child1.addChild(child2)


                #if value.get("category") in value.get("path"):
                #    if value.get("name") in value.get("path"):
                #        child1 = QTreeWidgetItem(self.treeWidget)
                #        child1.setText(0, value.get("category"))
#
                #        child2 = QTreeWidgetItem()
                #        child2.setText(0, value.get("name"))
                #        child1.addChild(child2)
#
                #if value.get("category") != value.get("name"):
                #    child1 = QTreeWidgetItem(self.treeWidget)
                #    child1.setText(0, value.get("category"))
                    #if value.get("category") == value.get("name") :
                    #    print('1111')
                    #    child2txt = (value.get(valueKey))
                    #    child2 = QTreeWidgetItem()
                    #    child2.setText(0, child2txt)
                    #    child1.addChild(child2)




            #for k,v in result.items():
            #    print(k)
            '''     
        for  i in  os.listdir(Path):
            child1 = QTreeWidgetItem(self.treeWidget)
            child1.setText(0,i)
            if os.path.isdir(os.path.join(Path,i)):
                for childPath2 in os.listdir(os.path.join(Path,i)):
                    child2 = QTreeWidgetItem(child1)
                    child2.setText(0, childPath2)
'''

        '''
        # newPath = os.path.split(newPath)[0]
        self.dir_level(newPath, child1)
        
        if os.path.isdir(Path):
            for wenjianjia in os.listdir(Path):
                newPath = os.path.join(Path, wenjianjia)
                if not os.path.isfile(newPath):

                    newPath = newPath.replace("\\", "/")
                    child1 = QTreeWidgetItem(item)
                    #newPath = os.path.split(newPath)[0]
                    self.dir_level(newPath, child1)

                    if os.path.isdir(newPath):
                        #print(newPath.split("/")[-1])
                        child1.setText(0, newPath.split("/")[-1])
'''


        #if self.treeWidget.parent():
        #    self.treeWidget.parent().removeChild(self.treeWidget)

        #if os.path.isdir(Path):
        #    for wenjianjia in os.listdir(Path):
        #        newPath = os.path.join(Path, wenjianjia)
        #        child1 = QTreeWidgetItem(item)
        #        self.dir_level(newPath, child1)
        #        print(newPath.split("/")[-1])
        #        child1.setText(0, newPath.split("/")[-1])
#

        '''
        for f in l:
            child1.setText(0, f[1])
            self.dir_level(Path, child1)
        
        l = []

        for root, dirs, files in os.walk(Path):
            d = []
            level = root.replace(Path, '').count(os.sep)
            #print(level)
            num = '-' * level
            #print(num)
            d.append(level)
            #print(d)
            root1=os.path.split(root)
            #print(root1)
            d.append(root1[1])
            #print(d)
            num= '-' * (level + 1)
            l.append(d)
            child1 = QTreeWidgetItem(item)
            for f in l:

                child1.setText(0,f[1])
                self.dir_level(Path,child1)
            '''

        '''
            for f in files:
                d = []
                d.append(level+1)
                d.append(num+f)
                l.append(d)
        for i in l:
            print (i)'''

class FlowLayout(QLayout):
    def __init__(self, parent=None, margin=0, spacing=-1):
        super(FlowLayout, self).__init__(parent)

        if parent is not None:
            self.setContentsMargins(margin, margin, margin, margin)

        self.setSpacing(spacing)

        self.itemList = []

    def __del__(self):
        item = self.takeAt(0)
        while item:
            item = self.takeAt(0)

    def addItem(self, item):
        self.itemList.append(item)

    def count(self):
        return len(self.itemList)

    def clear(self):  # real signature unknown; restored from __doc__
        """ clear(self) -> None """
        self.itemList.clear()

    def itemAt(self, index):
        if index >= 0 and index < len(self.itemList):
            return self.itemList[index]

        return None

    def deleteLater(self):  # real signature unknown; restored from __doc__
        """ deleteLater(self) """
        pass

    def takeAt(self, index):
        if index >= 0 and index < len(self.itemList):
            return self.itemList.pop(index)

        return None

    def expandingDirections(self):
        return Qt.Orientations(Qt.Orientation(0))

    def hasHeightForWidth(self):
        return True

    def heightForWidth(self, width):
        height = self.doLayout(QRect(0, 0, width, 0), True)
        return height

    def setGeometry(self, rect):
        super(FlowLayout, self).setGeometry(rect)
        self.doLayout(rect, False)

    def sizeHint(self):
        return self.minimumSize()

    def minimumSize(self):
        size = QSize()

        for item in self.itemList:
            size = size.expandedTo(item.minimumSize())

        margin, _, _, _ = self.getContentsMargins()

        size += QSize(2 * margin, 2 * margin)
        return size

    def doLayout(self, rect, testOnly):
        x = rect.x()
        y = rect.y()
        lineHeight = 0

        for item in self.itemList:
            wid = item.widget()
            spaceX = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton,
                                                                QSizePolicy.PushButton, Qt.Horizontal)
            spaceY = self.spacing() + wid.style().layoutSpacing(QSizePolicy.PushButton,
                                                                QSizePolicy.PushButton, Qt.Vertical)
            nextX = x + item.sizeHint().width() + spaceX
            if nextX - spaceX > rect.right() and lineHeight > 0:
                x = rect.x()
                y = y + lineHeight + spaceY
                nextX = x + item.sizeHint().width() + spaceX
                lineHeight = 0

            if not testOnly:
                item.setGeometry(QRect(QPoint(x, y), item.sizeHint()))

            x = nextX
            lineHeight = max(lineHeight, item.sizeHint().height())

        return y + lineHeight - rect.y()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = mainWindow()
    mainWindow.show()
    sys.exit(app.exec())